/*
 * @Date: 2025-02-27 10:28:34
 * @Auth: 873768511@qq.com
 * @LastEditors: 463997479@qq.com
 * @LastEditTime: 2025-10-06 10:53:32
 * @FilePath: \corpus\src\pages\resourceManagement\list\hooks\index.ts
 */
import type { ActionType, FormInstance } from '@ant-design/pro-components';
import { useRequest, useToggle } from 'ahooks';
import { Form, message } from 'antd';
import { createContainer } from 'unstated-next';
// import {

// } from '@/services/rulesCenter/modelManagement/list';
import { editKnowledge } from '@/services/ant-design-pro/home';
import {
  addCorpusBase,
  addFileByCorpus,
  addNewKnowledge,
  addResourceGroup,
  corpusFileTaskBrief,
  deleteCorpusBase,
  deleteCorpusFile,
  deleteResourceGroup,
  editCorpusBase,
  editResourceGroup,
  getCorpusBaseList,
  getCorpusFileList,
  getCorpusFileTask,
  getFilePage,
  getFileTaskPage,
  getKnowledgeChunk,
  getNewList,
  getResource,
  getResourceGroupList,
  retryCorpusFileTask,
  saveFileByCorpus,
} from '@/services/ant-design-pro/resource';
import { useLocation, useModel } from '@umijs/max';
import { useRef, useState } from 'react';
interface TabsType {
  [key: string]: {
    name: string;
    key: string;
  };
}
const tabsType: TabsType = {
  file: {
    key: '1',
    name: '原始数据资源',
  },
  knowledge: {
    key: '2',
    name: '知识库',
  },

  corpus: {
    key: '3',
    name: '语料库',
  },
};
export default createContainer(() => {
  const [tabKey, setTabKey] = useState('file');
  const { actionRef, name, selectedKeys } = useModel('useTree', (model) => {
    return {
      actionRef: model.actionRef,
      name: model.name,

      selectedKeys: model.selectedKeys,
    };
  });
  const [formAnalysis] = Form.useForm();
  const [newList, setNewList] = useState<any[]>([]);

  const location: Record<string, any> = useLocation();

  const resourceId = location?.state?.resourceId ? location?.state?.resourceId : '';
  const knowledgeCode = location?.state?.dsCode ? location?.state?.dsCode : '';

  // 抽屉
  const [drawerDetail, { toggle: drawerDetailToggle }] = useToggle();

  const [corpusDrawerDetail, { toggle: corpusDrawerDetailToggle }] = useToggle();

  const [drawerTask, { toggle: drawerTaskToggle }] = useToggle();
  const [resourceData, setResourceData] = useState(null);
  const [resourceKnowledgeData, setResourceKnowledgeData] = useState(null);
  const [knowledgeDrawerDetail, { toggle: knowledgeDrawerDetailToggle }] = useToggle();

  const [modalVisible, setModalVisible] = useState(false);
  const [corpusVisible, setCorpusVisible] = useState(false);
  const [modalKnowledgeVisible, setModalKnowledgeVisible] = useState(false);
  const [dsCode, setDsCode] = useState('');
  const [fileId, setFileId] = useState('');

  const [corpusData, setCorpusData] = useState(null);
  const [keyWord, setKeyWord] = useState('');

  const [formResource] = Form.useForm();
  const [forKnowledgemRef] = Form.useForm();
  const [createKnowledgeVisible, setCreateKnowledgeVisible] = useState<boolean>(false);

  const tableRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [total, setTotal] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<React.Key[]>([]);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  // 删除
  const deleteResourceGroupData = useRequest(
    async (id) => {
      const res = await deleteResourceGroup(id);
      if (res?.success) {
        message.success('删除成功');
        actionRef?.current?.reload();
      }
    },
    { manual: true },
  );
  const deleteCorpusFileContent = useRequest(
    async (id) => {
      const res = await deleteCorpusFile(id);
      if (res?.success) {
        message.success('删除成功');
        actionRef?.current?.reload();
      }
    },
    { manual: true },
  );

  const editResourceGroupData = useRequest(
    async (id) => {
      const res = await editResourceGroup(id);
      if (res?.success) {
        message.success('修改成功');

        setModalVisible(false);
        actionRef?.current?.reload();
      }
    },
    { manual: true },
  );

  const getData = useRequest(
    async (val: any) => {
      const res = await getNewList({
        ...val,
        deptCode: selectedKeys.toString(),
        content: keyWord,
      });
      setTotal(res?.total ?? 0);
      return {
        data: res?.data || [],
        total: res?.total || 0,
        success: res?.success,
      };
    },
    { manual: true },
  );

  const addResourceGroupData = useRequest(
    async (val) => {
      const res = await addResourceGroup({
        ...val,
        deptCode: currentUser?.deptCode,
      });
      if (res?.success) {
        message.success('添加成功');
        setModalVisible(false);
        actionRef?.current?.reload();
      }
    },
    { manual: true },
  );

  const getTableList = useRequest(
    async ({ ...query }) => {
      console.log(query);
      const res = await getResourceGroupList({
        ...query,
        deptCode: currentUser?.deptCode,
        content: keyWord,
      });
      setTotal(res?.total ?? 0);
      return {
        data: res?.data || [],
        total: res?.total || 0,
        success: res?.success,
      };
    },
    {
      manual: true,
    },
  );
  const getCorpusBase = useRequest(
    async ({ ...query }) => {
      console.log(query);
      const res = await getCorpusBaseList({
        ...query,
        content: keyWord,
        deptCode: currentUser?.deptCode,
      });
      setTotal(res?.total ?? 0);
      return {
        data: res?.data || [],
        total: res?.total || 0,
        success: res?.success,
      };
    },
    {
      manual: true,
    },
  );
  const getCorpusFile = useRequest(
    async ({ ...query }) => {
      console.log(query);
      const res = await getCorpusFileList({
        ...query,
        corpusBaseId: resourceId,
      });
      return {
        data: res?.data || [],
        total: res?.total || 0,
        success: res?.success,
      };
    },
    {
      manual: true,
    },
  );
  const getCorpusFileTaskList = useRequest(
    async ({ ...query }) => {
      const res = await getCorpusFileTask({
        ...query,
        corpusFileId: fileId,
      });
      return {
        data: res?.data || [],
        total: res?.total || 0,
        success: res?.success,
      };
    },
    {
      manual: true,
    },
  );
  const getKnowledgeChunkContent = useRequest(
    async ({ ...query }) => {
      const res = await getKnowledgeChunk({
        ...query,
        dsCode: knowledgeCode,
      });
      return {
        data: res?.data || [],
        total: res?.total || 0,
        success: res?.success,
      };
    },
    {
      manual: true,
    },
  );

  const getNewListContent = useRequest(
    async (val) => {
      const res = await getNewList(val);
      if (res?.data) {
        setNewList(res.data);
      }
    },
    { manual: true },
  );
  const getFilePageContent = useRequest(
    async ({ ...query }) => {
      const res = await getFilePage({
        ...query,

        dsCode: dsCode,
      });
      return {
        data: res?.data || [],
        total: res?.total || 0,
        success: res?.success,
      };
    },
    {
      manual: true,
    },
  );

  const getFileTaskPageContent = useRequest(
    async (val) => {
      const res = await getFileTaskPage({
        fileCode: val.fileCode,
        dsCode: dsCode,
      });
      return {
        data: res?.data || [],
        total: res?.total || 0,
        success: res?.success,
      };
    },
    {
      manual: true,
    },
  );

  const editKnowledgeContent = useRequest(
    async (vals: object) => {
      const res: any = await editKnowledge({
        ...vals,
      });

      if (res) {
        message.success('修改成功', 0.6);
        actionRef.current?.reload();
      } else {
        message.error(`标签信息更新失败，错误信息：!`, 0.5);
      }
    },

    { manual: true },
  );

  const editCorpusBaseContent = useRequest(
    async (vals: object) => {
      const res: any = await editCorpusBase({
        ...vals,
      });

      if (res) {
        message.success('修改成功', 0.6);
        setCorpusVisible(false);

        actionRef.current?.reload();
      } else {
        message.error(`标签信息更新失败，错误信息：!`, 0.5);
      }
    },

    { manual: true },
  );

  const addCorpusBaseData = useRequest(
    async (val) => {
      const res = await addCorpusBase({ ...val, deptCode: currentUser?.deptCode });
      if (res?.success) {
        message.success('添加成功');
        setCorpusVisible(false);
        actionRef?.current?.reload();
      }
    },
    { manual: true },
  );
  const addResourceFileKnowledgeContent = useRequest(
    async (id) => {
      const res = await addFileByCorpus(id);
      if (res?.success) {
        message.success('生成成功');
        setCreateKnowledgeVisible(false);
        tableRef?.current?.reload();
      }
    },
    { manual: true },
  );

  const saveFileByCorpusContent = useRequest(
    async (val) => {
      const res = await saveFileByCorpus({
        ...val,
      });
      if (res?.success) {
        message.success('生成成功');
        setCreateKnowledgeVisible(false);
        tableRef?.current?.reload();
      }
    },
    { manual: true },
  );

  const getCorpusFileTaskBrief = useRequest(
    async (id) => {
      const res = await corpusFileTaskBrief(id);
      return res;
    },
    { manual: true },
  );

  const getRetryCorpusFileTask = useRequest(
    async (id) => {
      const res = await retryCorpusFileTask(id);
      if (res?.data) {
        message.success('重试成功，任务进行中，请稍后再查看。');
        actionRef?.current?.reload();
      }
    },
    { manual: true },
  );
  const deleteCorpusBaseData = useRequest(
    async (id) => {
      const res = await deleteCorpusBase(id);
      if (res?.success) {
        message.success('删除成功');
        actionRef?.current?.reload();
      }
    },
    { manual: true },
  );

  const addNewKnowledgeContent = useRequest(
    async (val) => {
      const res = await addNewKnowledge({
        ...val,
        deptCode: currentUser?.deptCode,
      });
      if (res?.success) {
        message.success('添加成功');
        setModalKnowledgeVisible(false);
        actionRef.current?.reload();
      }
    },
    { manual: true },
  );

  const resourceDetail = useRequest(async () => {
    const res = await getResource({ deptCode: currentUser?.deptCode });
    return res.data;
  });
  return {
    tableRef,
    formRef,
    drawerDetail,
    drawerDetailToggle,
    deleteResourceGroupData,
    modalVisible,
    setModalVisible,
    tabKey,
    setTabKey,
    resourceDetail,
    tabsType,
    drawerTask,
    drawerTaskToggle,
    addResourceGroupData,
    formResource,
    resourceData,
    setResourceData,
    total,
    getTableList,
    setKeyWord,
    getData,
    editResourceGroupData,
    setTotal,
    editKnowledgeContent,
    addNewKnowledgeContent,
    resourceKnowledgeData,
    setResourceKnowledgeData,
    modalKnowledgeVisible,
    setModalKnowledgeVisible,
    forKnowledgemRef,
    getFilePageContent,
    setDsCode,

    getFileTaskPageContent,
    getCorpusBase,
    corpusVisible,
    setCorpusVisible,
    editCorpusBaseContent,
    addCorpusBaseData,
    deleteCorpusBaseData,
    corpusData,
    setCorpusData,
    getCorpusFile,
    deleteCorpusFileContent,
    getCorpusFileTaskList,
    corpusDrawerDetailToggle,
    corpusDrawerDetail,
    setFileId,

    getKnowledgeChunkContent,
    knowledgeDrawerDetail,
    knowledgeDrawerDetailToggle,
    selectedRowKeys,
    setSelectedRowKeys,
    selectedRows,
    setSelectedRows,
    createKnowledgeVisible,
    setCreateKnowledgeVisible,
    formAnalysis,
    newList,
    setNewList,
    getNewListContent,
    addResourceFileKnowledgeContent,
    getCorpusFileTaskBrief,
    saveFileByCorpusContent,
    getRetryCorpusFileTask,
  };
});
